package com.frame.flux.action.creator;

import android.os.Bundle;

import com.data.entity.Image;
import com.frame.flux.action.MainAction;
import com.frame.flux.dispatcher.Dispatcher;
import com.frame.flux.manager.BundleKey;
import com.frame.flux.manager.BundleUtil;
import com.frame.flux.manager.DataLayer;
import com.util.helper.RxSchedulers;

import rx.Observable;

/**
 * @Description
 * @Author luxiao418
 * @Email luxiao418@pingan.com.cn
 * @Date 16/8/13 12:32
 * @Version v2.6.0
 */
public class MainActionCreator extends BaseActionCreator {

    public MainActionCreator(Dispatcher dispatcher, DataLayer dataLayer) {
        super(dispatcher, dataLayer);
    }

    public void fetchMianList(){

        //分发开始刷新列表事件
        getDispatcher().dispatch(new MainAction(MainAction.ACTION_LIST_MAIN_FETCH_START));

        //缓存数据源
        Observable<Image> cache = getDataLayer().getDailyService().getLocalMainList();

        //缓存数据源
        Observable<Image> network = getDataLayer().getDailyService().getMainList();

        //输出前缓存一下
        network = network.doOnNext(image ->getDataLayer().getDailyService().cacheMainList(image));

        //没有网络数据再使用缓存数据
        Observable<Image> source = Observable.concat(network, cache).first(image -> image != null);//return image;

        source.compose(RxSchedulers.io_main()).subscribe(image -> {
            //封装数据
            Bundle bundle = BundleUtil.newInstance();
            bundle.putSerializable(BundleKey.MIAN_LIST, image);
            //分发Action
            getDispatcher().dispatch(new MainAction(MainAction.ACTION_LIST_MIAN_FETCH_FINISH, bundle));
        }, throwable -> {
            //封装异常
            Bundle bundle = BundleUtil.withThrowable(throwable);
            //分发Action
            getDispatcher().dispatch(new MainAction(MainAction.ACTION_LIST_MAIN_FETCH_ERROR, bundle));
        });
    }

}
